﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerConsole
{
    enum OutgoingCommandTable : byte
    {
        OpdateHighestBid = 1,
        SendLotInfo = 2,
        LotSold = 3,
        UserLogedIn = 4
    }

    public delegate void ShutDownHandler();

    class Server
    {
        public event ShutDownHandler Notifyshutdown;
        
        #region fields
        ClientsMonitor _Monitor;
        Auction _Auction;
        
        private const int PORT = 12345; // hardkodet = fyfy, men vi har andre prioriteter lige nu.
        private bool bPendingShutdown = false; // et flag der definerer om vi skal lukke ned.
        #endregion

        #region properties

        public bool PendingShutDown
        {
            get { return bPendingShutdown; }

            set
            {
                bPendingShutdown = value;
                Notifyshutdown();
            }
        }
        #endregion

        #region Constructors

        /// <summary>
        /// instantierer et nyt objekt af typen server.
        /// </summary>
        /// <param name="bShouldStartAutomaticly"> hvis true så starter serveren af sig selv. bShouldStartAutomaticly er true som standard</param>
        public Server(bool bShouldStartAutomaticly = true)
        {
            if (bShouldStartAutomaticly)
            {
                RunServer();
            }

            Notifyshutdown += NotifyServerShutdown;
            _Auction.AuctionStarted += new AuctionEvnetHandler(OnAuctionStarted);
            _Auction.AuctionEnded += new AuctionEvnetHandler(OnAuctionEnded);
            _Auction.NewLotSet += new AuctionEvnetHandler(OnNewLotSet);
        }
        #endregion

        #region Methods
        void NotifyServerShutdown()
        {
            //TODO
            // find alle klient trådene
            // gør alle trådene opmærksom på at de skal stoppe.
            throw new NotImplementedException();
        }

        public void RunServer()
        {
            IPEndPoint _Port;
            Socket _ClientSocket;
            ClientThreads _ClientThreads;

            Thread _ClientThread;
            ThreadStart _ThreadingMethod;
            Socket Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _Port = new IPEndPoint(IPAddress.Any, PORT);
            // _Auction = new Auction();

            Listener.Bind(_Port);
            Listener.Listen(100); //vi kan have 100 klienter. Mere end rigligt.

            _Monitor = new ClientsMonitor(); //Vi skal have en snak om designet så vi alle ved hvad der foregår især mig.

            while (!bPendingShutdown) //så længe vi ikke får besked på at lukke ned.
            {
                Console.WriteLine("Venter på klienter");
                _ClientSocket = Listener.Accept();
                
                Console.WriteLine("Klient logget på");


                _ClientThreads = new ClientThreads(_Monitor, _ClientSocket, _Auction); // er ikke implementeret endnu.
                _ThreadingMethod = _ClientThreads.HandleClient;
                _ClientThread = new Thread(_ThreadingMethod);
                _ClientThread.Start();
            }
        }

        private void OnAuctionStarted()
        {
            _Monitor.BroadCastAuctionStarted();
        }

        private void OnAuctionEnded()
        {
            _Monitor.BroadCastAuctionEnded();
        }

        private void OnHammerStroke()
        {
            _Monitor.BroadCastHammerStroke();
        }

        private void OnNewLotSet()
        {
            //_Monitor.BroadCastNewLot();
        }

        public void InitiateShutDown()
        {

        }
        #endregion


    }
}
